import useStore from '../store';
import {
	setOpenidStatus
} from './openId';
import {
	removeUserinfo
} from './user';
import {
	getUserIdentity,
	navTo,
	navigateValidate,
	rgoto,
	setLoadingToast,
	setToast,
	sgoto
} from './utils';

// showErrorMsg 是否需要提示tootip
const DONT_NEED_TOOTIP_CODE = [401]
let code403 = false

function httpInterception(response) {
	const {
		code,
		msg
	} = response
	// 报错
	console.log('code ===> ', code);
	if (!DONT_NEED_TOOTIP_CODE.includes(code) && code !== 1) {
		setToast(msg)
	}
	// 处理事件
	EVENT[code] && EVENT[code](response)
}

const EVENT = {
	401: notLogin
}

const alertModel = (clear, config = {}) => {
	uni.showModal({
		title: '系统提示',
		content: '您的令牌已过期或已登出, 请重新登陆',
		showCancel: false,
		cancelText: '',
		confirmText: '去登陆',
		...config,
		success: res => {
			console.log('res ===> ', res);
			if (res.confirm) {
				setLoadingToast('退出中...')
				clear && clear()
				setOpenidStatus(0)
				const href = window.location.href
				setTimeout(() => {
					navigateValidate(href)
					uni.hideLoading()
				}, 200)
			}
		},
		fail: () => {},
		complete: () => {}
	});
}

// 未登录或令牌失效 401
export function notLogin(config) {
	const {
		// 物流公司
		useLogisicsCompany,
		// 司机
		useLogisicsDriver,
		// 宇硕
		useLogisicsYushuo,
		// 微信
		useWx
	} = useStore();
	// 获取权限
	const userIdentity = getUserIdentity();
	// 首先清空wx获取的code的状态，因为如果是1的话，就不会继续获取
	setOpenidStatus(0)
	// 按需处理
	if (userIdentity) {
		switch (userIdentity.role) {
			case "logisticsCompany":
				const company = useLogisicsCompany
				if (company) {
					alertModel(company.clear, config)
				}
				break;
			case "driver":
				const driver = useLogisicsDriver
				if (driver) {
					alertModel(driver.clear, config)
				}
				break;
			case "yuShuo":
				const yushuo = useLogisicsYushuo
				if (yushuo) {
					alertModel(yushuo.clear, config)
				}
				break;
			default:
				break;
		}
	} else {
		const current = getCurrentPages()
		if (current[0]) {
			const route = current[0].route.split('/')
			if (route[1] !== 'index') {
				uni.reLaunch({
					url: `/pages/${route[1]}/login/login`
				})
			}
		}
	}

}

export default httpInterception